import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:talk/api/ShareApi.dart';
import 'package:talk/pages/provider/specifics_pick_component.dart';

import '../../api/DeviceApi.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../tools/widgets/my_app_bar.dart';

// 导入你的日期选择组件（确保路径正确）
import '../../utils/toast_utils.dart';
import 'date_range_picker_component.dart';

class SpecificsSelectPage extends StatefulWidget {
  const SpecificsSelectPage({
    super.key,
    this.shareId,
    this.endTime,
  });

  final int? shareId;
  final String? endTime;

  @override
  State<SpecificsSelectPage> createState() => _DataSelectPageState();
}

class _DataSelectPageState extends State<SpecificsSelectPage> {
  final DeviceApi _deviceApi = DeviceApi();
  final ShareApi _shareApi = ShareApi();
  late int _shareId;
  late String _endTime;

  // 选中状态管理：true-永久有效，false-选择日期
  bool _isPermanentSelected = true;
  // 存储选中的日期
  DateTime? _selectedDate;

  @override
  void initState() {
    super.initState();
    _shareId = widget.shareId!;
    _endTime = widget.endTime!;
    print("object");
    print(_endTime);
    // 初始化选中日期（从data参数解析）
    _selectedDate = _parseDateFromString(_endTime);
  }

  // 从字符串解析日期
  DateTime? _parseDateFromString(String dateStr) {
    try {
      final parts = dateStr.split('-');
      if (parts.length != 3) return null;
      return DateTime(
        int.parse(parts[0]),
        int.parse(parts[1]),
        int.parse(parts[2]),
      );
    } catch (e) {
      return null;
    }
  }

  // 构建单选圆圈组件
  Widget _buildRadioCircle(bool isSelected) {
    return Container(
      width: 20,
      height: 20,
      decoration: BoxDecoration(
        color: isSelected ? Colors.blue : Colors.white,
        shape: BoxShape.circle,
        border: Border.all(
          color: isSelected ? Colors.blue : Colors.blue.withOpacity(0.5),
          width: 2,
        ),
      ),
      child: isSelected
          ? const Center(
        child: SizedBox(
          width: 8,
          height: 8,
          child: DecoratedBox(
            decoration: BoxDecoration(
              color: Colors.white,
              shape: BoxShape.circle,
            ),
          ),
        ),
      )
          : null,
    );
  }


  Future<void> _updateDataSelect() async {

    final toUpdate = {
      "shareId": _shareId,
      "endTime": _selectedDate.toString(),
      "isSelect": _isPermanentSelected,
    };
    final response = await _shareApi.updateDataSelect(toUpdate);
    if (response.code == 200) {
      setState(() {

      });
    } else {
      Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('d_shijianduan'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
        showRightButton: true,
        rightButtonType: RightButtonType.text,
        rightButtonText: AppLocale.text('d_baocun'),
        rightButtonTextStyle: const TextStyle(
          color: Colors.blue,
          fontSize: 18,
        ),
        onRightButtonPressed: () async {

          // 等待更新操作完成
          await _updateDataSelect();
          // 只有更新成功后才返回（可选，根据需求调整）
          Navigator.maybePop(context);
        },
      ),
      body: Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 永久有效选项
            ItemView(
              width: 400,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  // 单选圆圈
                  _buildRadioCircle(_isPermanentSelected),
                  const SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_youxiaoqi'),
                    style: TextStyle(fontSize: 15.0, color: Colors.black),
                  ),
                ],
              ),
              rightWidget: Row(
                children: [
                  Text(
                    AppLocale.text('d_yongjiuyouxiao'),
                    style: TextStyle(fontSize: 15.0, color: Colors.black),
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {
                setState(() {
                  _isPermanentSelected = true;
                });
              },
            ),

            const SizedBox(height: 20),

            // 选择日期选项
            ItemView(
              width: 400,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  // 单选圆圈
                  _buildRadioCircle(!_isPermanentSelected),
                  const SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_xuanzheriqi'),
                    style: TextStyle(fontSize: 15.0, color: Colors.black),
                  ),
                ],
              ),
              rightWidget: Row(
                children: [
                  // 显示选中的时间段
                  Text(
                    _selectedDate != null
                        ? "${_selectedDate!.year}-${_selectedDate!.month.toString().padLeft(2, '0')}-${_selectedDate!.day.toString().padLeft(2, '0')}"
                        : AppLocale.text('d_weixuanzhe'),
                    style: const TextStyle(fontSize: 15.0, color: Colors.grey),
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {
                setState(() {
                  _isPermanentSelected = false;
                });
              },
            ),

            // 日期选择组件（仅在选择日期选项被选中时显示）
            if (!_isPermanentSelected)
              Padding(
                padding: const EdgeInsets.only(top: 1),
                child: DatePickerComponent(
                  title: AppLocale.text('d_shruuguanjianchi'),
                  width: 300,
                  data: _endTime,
                  initialDateTime: DateTime(2023, 10, 1),
                  onChanged: (selectedDate) {
                    setState(() {
                      _selectedDate = selectedDate;
                    });
                    // print("选中日期: ${selectedDate?.toLocal()}");
                  },
                ),
              ),
          ],
        ),
      ),
    );
  }
}